<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col">
        <el-form :inline="true" class="tm">
          <!-- <el-form-item label="学员">
            <el-select-v2
              :style="{ width: '200px' }"
              v-model="userids"
              :options="options"
              collapse-tags
              multiple
            >
            </el-select-v2>
          </el-form-item>-->
          <el-form-item label="时间">
            <el-date-picker
              v-model="times"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="查询">
            <el-button @click="submit">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div></div>
    </div>
    <div class="row">
      <h3>{{ data.name }}</h3>
    </div>
    <div class="row">
      <div class="col">
        <table class="table border">
          <tr>
            <td>登录人数（占比）:</td>
            <td>{{ Datalogindata }} %</td>
          </tr>
          <tr>
            <td>看题人数（占比）:</td>
            <td>{{ Datawatchquesiton }} %</td>
          </tr>
          <tr>
            <td>做题人数（占比）</td>
            <td>{{ Datemakequestion }} %</td>
          </tr>
          <tr>
            <td>看视频人数（占比）</td>
            <td>{{ Datawatchvideo }} %</td>
          </tr>
          <tr>
            <td>平均每人登录间隔（天）</td>
            <td>{{ averagelogindata }} 天</td>
          </tr>
          <tr>
            <td>平均每人看题间隔（天）</td>
            <td>{{ averagewatchquesiton }} 天</td>
          </tr>
          <tr>
            <td>平均每人做题间隔（天）</td>
            <td>{{ averagequestion }} 天</td>
          </tr>
          <tr>
            <td>平均每人看视频间隔（天）</td>
            <td>{{ averagewatchvideo }} 天</td>
          </tr>
          <tr>
            <td>评测0题人数（占比）</td>
            <td>{{ userquestiondata.zero }} %</td>
          </tr>
          <tr>
            <td>评测1题人数（占比）</td>
            <td>{{ userquestiondata.one }} %</td>
          </tr>
          <tr>
            <td>评测2-4题人数（占比）</td>
            <td>{{ userquestiondata.two_four }} %</td>
          </tr>
          <tr>
            <td>评测5+题人数（占比）</td>
            <td>{{ userquestiondata.attr }} %</td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Team } from "../../../admin/views/data";
import {
  asyncgetteam,
  asyncselectteamselectuser,
  asyncselectchart,
  ChartApitype,
} from "../../../api";
import { Storekey } from "../../../interface";
import FetchApi, { logdata } from "../../../logs/api";
import { OJMethod, OJtype } from "../../../logs/type";
import { shortcuts } from "../../../util/time";
import { ElMessage } from "element-plus";
import moment from "moment";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import { useStore } from "vuex";

export default defineComponent({
  props: {
    ID: Number,
  },
  setup(p) {
    const { ID } = toRefs(p);
    const 在线 = OJMethod["在线"];
    const pingc = OJtype["scoket"];
    const 查看题目 = OJMethod["查看题目"];
    const options = computed(() => {
      return users.value.map((e) => {
        return {
          value: e?.ID,
          label: e?.name,
        };
      });
    });
    const formInline = reactive<logdata>({
      query: "* | with_pack_meta",
      line: 99,
      offset: 0,
      projectName: "htetest1",
      logstoreName: "ojhte",
      from: new Date(moment().subtract(7, "days").unix() * 1000),
      to: new Date(moment().add(1, "days").unix() * 1000),
      reverse: true,
    });
    const times = computed<[Date, Date]>({
      get() {
        return [formInline.from, formInline.to];
      },
      set(v: [Date, Date]) {
        formInline.from = v[0];
        formInline.to = v[1];
      },
    });
    watch(
      () => times.value,
      () => {
        submit();
      }
    );
    const data = reactive(Object.assign({}, Team));
    const mydata = ref<ChartApitype>({ userquestion: [], userquestion2: [] });
    const store = useStore(Storekey);
    const userids = ref<number[]>([]);

    const user = computed<Studycodemodel.Iuser>(() => {
      return store.getters.getuser;
    });

    const users = computed(() => {
      return teamusers.value.map((e) => e.user).concat(data.user);
    });

    function rizhi() {
      if (isAdmin.value) {
        window.open("/");
      }
    }
    const logindata = ref<
      { _userid_: number; count: number; __time__: number }[]
    >([]);
    const watchquesitondata = ref<
      { _userid_: number; count: number; __time__: number }[]
    >([]);
    const watchvideodata = ref<
      { _userid_: number; count: number; __time__: number }[]
    >([]);
    const Datemakequestion = computed(() => {
      return Math.ceil(
        (mydata.value.userquestion2.length / users.value.length) * 100
      );
    });
    // 平均做题
    const averagequestion = computed(() => {
      const data = mydata.value.userquestion2
        .filter((e) => Number(e.count) > 1)
        .map((e) => e.count);
      const count = data.reduce((a, b) => Number(a) + Number(b), 0);
      const time =
        new Date(times.value[1]).getTime() - new Date(times.value[0]).getTime();
      return count
        ? Math.ceil(time / 1000 / 60 / 60 / 24 / (count / users.value.length))
        : 0;
    });

    // 做题统计 0 1 2-4 5+
    const userquestiondata = computed(() => {
      const zero = users.value.length - mydata.value.userquestion2.length;
      const one = mydata.value.userquestion2.filter(
        (e) => e.count === 1
      ).length;
      const two_four = mydata.value.userquestion2.filter(
        (e) => e.count > 1 && e.count < 5
      ).length;
      const attr = mydata.value.userquestion2.length - one - two_four;
      return {
        zero: Math.ceil((zero / users.value.length) * 100),
        one: Math.ceil((one / users.value.length) * 100),
        two_four: Math.ceil((two_four / users.value.length) * 100),
        attr: Math.ceil((attr / users.value.length) * 100),
      };
    });

    //登录半分比
    const Datalogindata = computed(() => {
      return Math.ceil((logindata.value.length / users.value.length) * 100);
    });
    // 平均登录间隔
    const averagelogindata = computed(() => {
      const data = logindata.value
        .filter((e) => Number(e.count) > 1)
        .map((e) => e.count);
      const count = data.reduce((a, b) => Number(a) + Number(b), 0);
      const time =
        new Date(times.value[1]).getTime() - new Date(times.value[0]).getTime();
      return count
        ? Math.ceil(time / 1000 / 60 / 60 / 24 / (count / users.value.length))
        : 0;
    });
    /**
     * 登录人数占比
     */
    async function getlogin1() {
      const query = `* and _teamids_:${p.ID} and _method_:"${在线}" | select _userid_, count(1) as count group by _userid_`;
      const data = await FetchApi(
        Object.assign({}, formInline, {
          query,
        })
      );
      logindata.value = data.data;
    }

    // 看题半分比
    const Datawatchquesiton = computed(() => {
      return Math.ceil(
        (watchquesitondata.value.length / users.value.length) * 100
      );
    });
    // 平均看题时间间隔
    const averagewatchquesiton = computed(() => {
      const data = watchquesitondata.value
        .filter((e) => Number(e.count) > 1)
        .map((e) => e.count);
      const count = data.reduce((a, b) => Number(a) + Number(b), 0);
      const time =
        new Date(times.value[1]).getTime() - new Date(times.value[0]).getTime();
      return count
        ? Math.ceil(time / 1000 / 60 / 60 / 24 / (count / users.value.length))
        : 0;
    });

    /**
     * 看题人数占比
     */
    async function watchquesiton() {
      const query = `* and _method_:"${查看题目}" and _teamids_:${p.ID} | select _userid_, count(1) as count group by _userid_`;
      const data = await FetchApi(
        Object.assign({}, formInline, {
          query,
        })
      );
      watchquesitondata.value = data.data;
    }

    /**
     * 做题人数占比
     */
    function makequesiotn() { }

    // 看视频半分比
    const Datawatchvideo = computed(() => {
      return Math.ceil(
        (watchquesitondata.value.length / users.value.length) * 100
      );
    });

    // 平均看视频时间间隔
    const averagewatchvideo = computed(() => {
      const data = watchvideodata.value
        .filter((e) => Number(e.count) > 1)
        .map((e) => e.count);
      const count = data.reduce((a, b) => Number(a) + Number(b), 0);
      const time =
        new Date(times.value[1]).getTime() - new Date(times.value[0]).getTime();
      return count
        ? Math.ceil(time / 1000 / 60 / 60 / 24 / (count / users.value.length))
        : 0;
    });

    /**
     * 视频人数占比
     */
    async function watchvideo() {
      const query = `* and type:video and _teamids_:${p.ID} | select _phonenum_, count(1) as count group by _phonenum_`;
      const query2 = `* and type:video and _teamids_:${p.ID} | select _cid_, count(1) as count group by _cid_`;
      const data = await FetchApi(
        Object.assign({}, formInline, {
          query,
        })
      );
      const data2 = await FetchApi(
        Object.assign({}, formInline, {
          query: query2,
        })
      );
      const d: {
        _phonenum_: string;
        _cid_: string;
        count: number;
        __time__: string;
      }[] = data.data.concat(data2.data);
      const n: { _userid_: number; count: number; __time__: number }[] = [];

      d.forEach((e) => {
        const { _phonenum_, count, _cid_, __time__ } = e;
        const x = users.value.find((t) => {
          const z = t?.phonenum == _phonenum_;
          const f = t?.gid == _cid_;
          return z || f;
        });
        if (x && x.ID) {
          const z = n.find((e) => e._userid_ == x.ID);
          if (!z) {
            n.push({
              _userid_: x.ID,
              count,
              __time__: Number(__time__),
            });
          }
        }
      });
      watchvideodata.value = n;
    }

    /**
     * 老师平均登录间隔
     */
    function averageteacherlogin() { }

    const teamusers = ref<Studycodemodel.Iteamuser[]>([]);

    watch(
      () => p.ID,
      () => {
        start().then(() => {
          getUsers();
        });
      }
    );

    async function start() {
      if (typeof ID?.value === "number") {
        const d = await asyncgetteam({ ID: ID.value });
        Object.assign(data, d);
      } else {
        ElMessage.error("没有找到");
      }
    }

    const badge = reactive({
      sett: false,
    });

    async function getUsers() {
      if (typeof ID?.value === "number") {
        teamusers.value = await asyncselectteamselectuser({
          teamid: ID.value,
        });
        const m = teamusers.value.find((e) => e.jurisdiction === "1");
        if (m) {
          badge.sett = true;
        } else {
          badge.sett = false;
        }
      }
    }

    async function submit() {
      const [starttime, endtime] = times.value;
      if (p.ID) {
        getlogin1();
        watchquesiton();
        watchvideo();
        Promise.all([watchquesiton, getlogin1, watchvideo]).then((e) => {
          ElMessage.success("查询成功");
        });
        mydata.value = await asyncselectchart({
          starttime,
          endtime,
          teamid: p.ID,
          userids: userids.value,
          timetype: "%y-%m-%d",
        });
      }
    }

    onMounted(() => {
      start().then(() => {
        getUsers();
        submit();
      });
    });

    watch(
      () => user,
      () => {
        start();
      }
    );

    const isAdmin = computed(() => {
      if (!user.value) return false;
      if (data?.userid === user.value.ID) return 1;
      const a = data?.teamuser?.find((v) => v.userid === user.value.ID);
      if (a) {
        return a.isAdmin;
      }
      if (user.value.remarks === "销售助教") return 2;
      return false;
    });

    return {
      team: data,
      times,
      shortcuts,
      averagewatchquesiton,
      Datawatchvideo,
      Datalogindata,
      averagelogindata,
      Datawatchquesiton,
      averagewatchvideo,
      options,
      userids,
      logindata,
      watchquesitondata,
      watchvideodata,
      Datemakequestion,
      averagequestion,
      userquestiondata,
      submit,
      data
    };
  },
});
</script>

<style scoped>
</style>